<template>
    <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
            <el-form label-width="250px" :model="baseInfoForm" :rules="baseInfoFormRules" ref="baseInfoForm" @submit.native.prevent v-loading="loading">
                <el-form-item label="所属通信服务器：" prop='serverId'>
                    <el-select v-model="baseInfoForm.serverId" clearable>
                        <el-option
                            v-for="item in serverTypeList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.serverId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="主机等型号：" prop='protocolType'>
                    <el-select v-model="baseInfoForm.protocolType">
                        <el-option
                            v-for="(item, i) in protocolTypeList"
                            :key="'protocolType-' + i + '-' + String(item.id)"
                            :label="item.name"
                            :value="String(item.systemtype)">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="物联设备名称：" prop='name'>
                    <el-input v-model="baseInfoForm.name" auto-complete="off" placeholder="请输入物联设备名称"></el-input>
                </el-form-item>
                <el-form-item label="复位方式：" prop='resetMode'>
                    <el-select v-model="baseInfoForm.resetMode">
                        <el-option label="自复位" value="0"></el-option>
                        <el-option label="处理后复位" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="系统类型：" prop='fireSystemTypeId'>
                    <el-select v-model="baseInfoForm.fireSystemTypeId">
                        <el-option
                            v-for="item in fireSystemTypeList"
                            :key="'fireSystemTypeId-' + item.id"
                            :label="item.name"
                            :value="String(item.id)">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="物联设备类别：" prop='fcFacilitiesCategoryId'>
                    <el-select v-model="baseInfoForm.fcFacilitiesCategoryId">
                        <el-option
                            v-for="item in fcFacilitiesCategoryList"
                            :key="'fcFacilitiesCategoryId-' + String(item.id)"
                            :label="item.name"
                            :value="String(item.id)">
                        </el-option>
                    </el-select>
                </el-form-item>
                <template v-for="obj in sysTypeFormList">
                    <el-form-item v-for="(item, index) in obj.formItems" :key="'sysTypeFormItem-' + index + '-' + item.id" :label="item.name + (item.unit!='' ? `（${item.unit}）` : '') + '：'"> 
                        <el-input v-if="item.code != 'data_type_id'" v-model="item.val" :name="item.code" auto-complete="off" :placeholder="'请输入' + item.name"></el-input>
                    </el-form-item>
                </template>
                <el-form-item label="消防建筑结构：" prop='fireBuildingStructureId'>
                    <tree-select
                        class="fire-building-structure"
                        v-model="baseInfoForm.fireBuildingStructureId"
                        filterable
                        :width="336"
                        :data="buildList"
                        :defaultProps="buildDefaultProps"
                        :checkedKeys="defaultCheckedBuildId"
                        :nodeKey="buildNodeKey">
                    </tree-select>
                </el-form-item>
                <el-form-item label="具体位置：" prop='location'>
                    <el-input v-model="baseInfoForm.location" auto-complete="off" placeholder="请输入位置"></el-input>
                </el-form-item>
                <el-form-item label="厂家：" prop='producerId'>
                    <el-select v-model="baseInfoForm.producerId">
                        <el-option
                            v-for="item in producerList"
                            :key="'producerId-' + item.dictKey"
                            :label="item.dictValue"
                            :value="item.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="关联其他物联设备：" prop="relateFcfIds" id="defaultFcStructId">
                    <el-select multiple v-model="baseInfoForm.relateFcfIds" 
                        placeholder="请选择关联其他物联设备"
                        filterable
                        :filter-method="getFcfOptions"
                        :loading="relateFcIdsSelectloading">
                        <el-option
                            v-for="item in relateFcOptions"
                            :key="'relateFcfIds-' + String(item.id)"
                            :label="item.name"
                            :value="String(item.id)">
                        </el-option>
                        <el-pagination
                            @current-change="handleCurrentChange"
                            :current-page.sync="relateFcPageIndex"
                            small
                            layout="total, prev, pager, next"
                            :total="relateFcTotal">
                        </el-pagination>
                    </el-select>
                </el-form-item>
                <el-form-item label="关联视频：" prop='relateVideos' id="defaultVideoStructId">
                    <el-select multiple v-model="baseInfoForm.relateVideos"
                        placeholder="请选择关联视频"
                        filterable
                        :filter-method="getVideos"
                        :loading="relateVideoIdsSelectloading">
                        <el-option
                            v-for="item in videoList"
                            :key="'relateVideos-' + item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                        <el-pagination
                            @current-change="handleVideoCurrentChange"
                            :current-page.sync="relateVideoPageIndex"
                            small
                            layout="total, prev, pager, next"
                            :total="relateVideoTotal">
                        </el-pagination>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注：" prop='remarks'>
                    <el-input v-model="baseInfoForm.remarks" auto-complete="off" placeholder="请输入备注"></el-input>
                </el-form-item>
                <el-form-item label="设施图片：" prop='pictures'>
                    <el-upload
                        :action="QINIUUPLOADURL"
                        :multiple="false"
                        ref="upload"
                        list-type="picture-card"
                        :data="qiniuData"
                        :on-success="handleAvatarSuccess"
                        :on-remove="handleRemovePic"
                        :on-error="handleError"
                        :before-upload="beforeAvatarUpload"
                        :on-preview="$imgPreview"
                        :file-list="qiniuData.fileList"
                        :limit="1"
                        :on-exceed="handleExceed"
                        accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label-width="0" class="verifyidentity-button">
                    <el-button @click.stop="closeFun" round>取消</el-button>
                    <el-button type="primary" @click="saveBaseInfo('videoBaseInfoForm')" round>保存</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>
<script>
import TreeSelect from '@/libs/TreeSelect/Main'
import { qnToken} from '@/api/api'
import util from '@/utils/util'
import { getDictByCode } from '@/api/dic'
import { getFbsTree } from '@/api/fbs'
import { getFcfSelectList } from '@/api/fcf'
import { getRelateVideo, getList } from '@/api/video'
import { getFcfCInfo, getAssignFcfP, getFireCtlCategoryList, setFcfCPVal, updateFireCtlFacsStructure, getFcfCPVal } from '@/api/sysConfig'

export default {
    name: 'FireServiceMainten',
    props: {
        organizationId: {
            required: true
        },
        serverId: {
            default() {
                return ''
            }
        },
        serverTypeList: {
            required: true,
            default() {
                return []
            }
        },
        isTop: {
            required: true
        },
        parentId: {},
        oldInfo: {
            type: Object
        },
        closeFun: {
            type: Function,
            required: true
        },
    },
    components: { 
        TreeSelect
    },
    data() {
        return {
            loading: false,
            firstLoad: true,
            qiniuData:{//上传图片携带的参数
                token : "",
                key : "",
                fileList:[],
            },
            protocolTypeList: [], // 主机等型号下拉框数据
            fireSystemTypeList: [], // 系统类型下拉框数据
            fcFacilitiesCategoryList: [], // 消防设施类型下拉框数据
            fireBuildingStructureList: [], // 消防建筑结构
            // 建筑物
            buildList: [],
            buildDefaultProps: {
                children: 'nodes',
                label: 'text',
                value: 'id'
            },
            buildNodeKey: 'id',
            producerList: [], // 厂家下拉框数据
            defaultCheckedBuildId: [],
            // 关联其他物联设备
            relateFcIdsSelectloading: false,
            relateFcOptions: [],
            relateFcPageIndex: 1,
            relateFcTotal: 0,
            videoList: [], // 关联视频
            relateVideoPageIndex: 1,
            relateVideoTotal: 0,
            sysTypeFormList: [], // 物联设备类别属性表单
            baseInfoForm: {
                serverId: this.serverId,
                protocolType: '',
                name: '',
                resetMode: '0',
                fireSystemTypeId: '',
                fcFacilitiesCategoryId: '',
                fireBuildingStructureId: '',
                location: '',
                producerId: '',
                relateFcfIds : '',
                relateVideos : '',
                remarks: ''
            },
            baseInfoFormRules: {
                // serverId: [
                //     { required: true, message: '请选择所属通信服务器', trigger: 'change' }
                // ],
                protocolType: [
                    { required: true, message: '请选择主机等型号', trigger: 'change' }
                ],
                name: [
                    { required: true, message: '请输入物联设备名称', trigger: 'blur' }
                ],
                resetMode: [
                    { required: true, message: '请选择复位方式', trigger: 'change' }
                ],
                fireSystemTypeId: [
                    { required: true, message: '请选择系统类型', trigger: 'change' }
                ],
                fcFacilitiesCategoryId: [
                    { required: true, message: '请选择物联设备类别', trigger: 'change' }
                ],
                fireBuildingStructureId: [
                    { required: true, message: '请选择消防建筑结构', trigger: 'blur' }
                ],
                location: [
                    { required: true, message: '请输入具体位置', trigger: 'blur' }
                ],
                producerId: [
                    { required: true, message: '请选择厂家', trigger: 'change' }
                ],
            }
        }
    },
    created() {
        let that = this
        that.loading = true

        let p1 = new Promise((resolve, reject) => {
            that.getToken(() => {resolve('p1成功了')})
            
        })
        let p2 = new Promise((resolve, reject) => {
            // 主机等型号数据
            that.getProtocolTypeList(() => {resolve('p2成功了')})
            
        })
        let p3 = new Promise((resolve, reject) => {
            // 系统类型数据
            that.getFireSystemTypeList(() => {resolve('p3成功了')})
            
        })
        let p4 = new Promise((resolve, reject) => {
            // 消防建筑结构
            that.bindSelectFbs(() => {resolve('p2成功了')})
            
        })
        let p5 = new Promise((resolve, reject) => {
            // 厂家数据
            that.getProducerList(() => {resolve('p5成功了')})
            
        })
        let p6 = new Promise((resolve, reject) => {
            // 关联其他物联设备
            that.getFcfOptions('', false, () => {resolve('p6成功了')})
            
        })
        let p7 = new Promise((resolve, reject) => {
            // 关联视频
            that.getVideos('', false, () => {resolve('p7成功了')})
            
        })

        Promise.all([p1, p2, p3, p4, p5, p6, p7]).then((result) => {
            // 如果有历史值，设置回显
            if (that.oldInfo.id) {
                that.$nextTick(() => {
                    for(let key in that.baseInfoForm) {
                        if(that.oldInfo[key]) {
                            if(key == 'relateFcfIds') {
                                that.baseInfoForm[key] = String(that.oldInfo[key]).split(',')
                            } else {
                                that.baseInfoForm[key] = String(that.oldInfo[key])
                            }
                        }
                    }
                    // 消防建筑回显
                    that.defaultCheckedBuildId = String(that.oldInfo.fireBuildingStructureId).split(',')
                    // 设置上传图片初始值
                    that.oldInfo.fcfacilitiesPicUrl ? $.each(that.oldInfo.fcfacilitiesPicUrl.split(','), (index, url) => {
                        that.qiniuData.fileList.push({
                            name: that.oldInfo.name + index,
                            url: url
                        })
                    }) : ''
                    // 获取关联视屏
                    getRelateVideo({
                        relateObjType : 1,
                        relateObjId : that.oldInfo.id
                    }).then(res => {
                        if(res.status === 200) {
                            let arr = []
                            for(let i=0, len = res.data.length; i < len; i++) {
                                arr.push(res.data[i].id)
                            }
                            that.baseInfoForm.relateVideos = arr
                            that.$nextTick(() => {
                                if(arr.length > 0) {
                                    let $tags = $('#defaultVideoStructId .el-select__tags').find('.el-select__tags-text')
                                    for (let i=0, len=$tags.length; i < len; i++) {
                                        $tags[i].innerText = res.data[i].name
                                    }
                                }
                                that.loading = false
                            })
                        }
                    })
                    /*
                    * 解决带分页的下拉框回显值不在首页无法显示label问题
                    */
                    that.$nextTick(() => {
                        if(that.oldInfo.relateFcfIds != '') {
                            let $tags = $('#defaultFcStructId .el-select__tags').find('.el-select__tags-text')
                            let nameList = that.oldInfo.relateFcfNames.split(',')
                            for (let i=0, len=$tags.length; i < len; i++) {
                                $tags[i].innerText = nameList[i]
                            }
                        }
                        return false
                    })
                })
            } else {
                that.$nextTick(() => {
                    that.loading = false
                })
            }
            // console.log(result)
        }).catch((error) => {
            // console.log(error) 
        })
    },
    methods: {
        // 获取主机等型号下拉框数据
        getProtocolTypeList(callback) {
            let that = this
            that.protocolTypeList = []
            // 获取打点类型
            util.ilinkArrHandle.delDicArr_keyVal(81, (arr) => {
                that.protocolTypeList.push.apply(that.protocolTypeList, arr)
                callback && callback()
            })
        },
        // 获取系统类型
        getFireSystemTypeList(callback) {
            let that = this

            util.ilinkArrHandle.delDicArr_keyVal(55, function(arr){
                that.fireSystemTypeList = arr
                if(!that.oldInfo.id) {
                    // 默认选中第一个
                    that.baseInfoForm.fireSystemTypeId = arr.length > 0 ? String(arr[0].id) : ''
                }
                callback && callback()
            })
        },
        // 获取消防设施类型下拉框数据
        getFcFacilitiesCategoryList(val) {
            let that = this
            // 根据系统类型联动
            if(val) {
                getFireCtlCategoryList({
                    queryType: 0,
                    fireSystemId: val
                }).then(res => {
                    if(res.status === 200) {
                        that.fcFacilitiesCategoryList = res.data
                        if(!that.oldInfo.id) {
                            // 默认选中第一个
                            that.baseInfoForm.fcFacilitiesCategoryId = res.data.length > 0 ? String(res.data[0].id) : ''
                        }
                    }
                })
            }
        },
        // 获取设施类别详细信息
        getFcfCInfoList(id) {
            let that = this
            getFcfCInfo({
                id: id
            }).then(res => {
                if(res.status = 200) {
                    // 如果是编辑回显，获取填写的数据
                    if(that.oldInfo.id && that.firstLoad) {
                        getFcfCPVal({
                            fcfId : that.oldInfo.id
                        }).then(res => {
                            if(res.status === 200) {
                                that.handlerChildValue(res.data[0])
                            }
                        })
                        
                    } else {
                        that.handlerChild(res.data)
                    }
                    that.firstLoad = false
                }
            })
        },
        // 新增获取类别子表单
        handlerChild(data) {
            let that = this
            getAssignFcfP({
                id : data.id,
                isRelationChild: data.isRelationChild
            }).then(res => {
                if(res.status === 200) {
                    for(let i=0, len = res.data.length; i < len; i++) {
                        res.data[i]['val'] = ''
                    }
                    that.sysTypeFormList.push({
                        fcfInfo: data,
                        formItems: res.data
                    })
                }
            })
            
            if(data.isRelationChild == 1 && data.nodes) {
                for(let i=0, len=data.nodes.length; i < len; i++) {
                    that.handlerChild(data.nodes[i])
                }
            }
        },
        // 编辑获取类别子表单
        handlerChildValue(data) {
            let that = this

            if(data.properties) {
                that.sysTypeFormList.push({
                    fcfInfo: data,
                    formItems: data.properties,
                })
            }

            if(data.nodes && data.nodes.length > 0) {
                for(let i=0, len=data.nodes.length; i < len; i++) {
                    that.handlerChildValue(data.nodes[i])
                }
            }
        },		
        // 查询消防建筑物结构树
        bindSelectFbs(callback) {
            var that = this
            getFbsTree({
                organizationId: that.organizationId
            }).then(res => {
                if(res.status === 200 && res.data.length > 0) {
                    // res.data[0]['disabled'] = true
                    that.buildList = res.data
                    // 最顶选项禁用（恶心）
                    that.$nextTick(() => {
                        // let $line = $('.fire-building-structure .el-tree-node__content')
                        
                        // $($line[0]).addClass('is-disabled')
                        callback && callback()
                    })
                } else {
                    that.buildList = []
                }
            })
        },
        // 获取厂家数据
        getProducerList(callback) {
            let that = this
            getDictByCode({
                code: 2
            }).then(res => {
                if(res.status = 200) {
                    that.producerList = res.data.dictValueObj
                    callback && callback()
                }
            })
        },
        // 获取关联其他物联设备
        getFcfOptions(name, pageChange, callback) {
            let that = this
            // 重新搜索时页码复原   
            if(!pageChange) {
                this.relateFcPageIndex = 1
            }
            let parames = {
                fbsId: 0,
                organizationId: that.organizationId,
                parentId: 0,
                pageIndex: this.relateFcPageIndex - 1,
                pageSize: 10,
                name: name || ''
            } 
            that.relateFcIdsSelectloading = true
            getFcfSelectList(parames).then(res => {
                if(res.status === 200) {
                    that.relateFcOptions = res.data
                    that.relateFcTotal = res.total
                }
                that.relateFcIdsSelectloading = false
                callback && callback()
            })
        },
        handleCurrentChange(currentpage) {
            this.relateFcPageIndex = currentpage
            this.getFcfOptions($('#defaultFcStructId .el-select__input').val(), true)
        },
        // 获取关联视频数据
        getVideos(name, pageChange, callback) {
            let that = this
            // 重新搜索时页码复原   
            if(!pageChange) {
                this.relateVideoPageIndex = 1
            }
            let parames = {
                organizationId: that.organizationId,
                queryType: 1,
                pageIndex: that.relateVideoPageIndex - 1,
                pageSize: 10,
                name: name || ''
            }
            that.relateVideoIdsSelectloading = true
            getList(parames).then(res => {
                if(res.status === 200) {
                    that.videoList = res.data
                    that.relateVideoTotal = res.total
                }
                that.relateVideoIdsSelectloading = false
                callback && callback()
            })
        },
        handleVideoCurrentChange(currentpage) {
            this.relateVideoPageIndex = currentpage
            this.getVideos($('#defaultVideoStructId .el-select__input').val(), true)
        },
        getToken(callback){  //上传之前获取 token
            qnToken({}).then((result) => {
                this.qiniuData.token= result.data
                callback && callback()
            })
        },
        beforeAvatarUpload: function(file){//重命名和校验
            var fielLocal = file.name.split(".")
            var fielType = "." + fielLocal[fielLocal.length-1]
            var fielLocalName = fielLocal[0]
            this.qiniuData.key = 'assesImg'+'_'+new Date().getTime()+fielType
            //this.qiniuData.key = file.name;
            const isJPG = file.type === "image/jpeg";
            const isPNG = file.type === "image/png";
            const isLt20M = file.size / 1024 / 1024 < 20;
            if (!isJPG && !isPNG) {
                this.$message.error("图片只能是 JPG/PNG 格式!")
                return false;
            }
            if (!isLt20M) {
                this.$message.error("图片大小不能超过 20MB!")
                return false;
            }
        },
        handleAvatarSuccess: function(res, file, fileList) {//上传成功
            this.qiniuData.fileList = fileList
        },
        handleRemovePic: function(file, fileList) {//删除成功
            this.qiniuData.fileList = fileList
        },
        handleError: function(res) {
            this.$message({
                message: "上传失败",
                duration: 2000,
                type: "warning"
            })
        },
        handleExceed(files, fileList) {//文件超出个数限制时的钩子
            this.$message.warning(`只能上传1张图片！`)
        },
        saveBaseInfo() {
            let that = this
            // 校验表单
            that.$refs['baseInfoForm'].validate((valid) => {
                if (valid) {
                    let parames = {
                        id : that.oldInfo.id || 0,
                        organizationId : that.organizationId,
                        isTop : that.isTop,
                        parentId : that.parentId || 0,
                        // serverId : that.serverId,
                        businessId: that.oldInfo.businessId || '',
                    }
                    $.extend(parames, that.baseInfoForm)
                    parames.relateFcfIds = parames.relateFcfIds.join(",")
                    parames.relateVideos = parames.relateVideos.join(",")
                    // 关联图片
                    parames.fcfacilitiesPicUrl = util.ilinkArrHandle.getqiniuPicUrlArr(that.qiniuData.fileList).toString()
                    // 提交
                    updateFireCtlFacsStructure(parames).then(res => {
                        if(res.status === 200) {
                            let propertyVal = []
                            for(let n=0, len=that.sysTypeFormList.length; n < len; n++) {
                                let properties = []
                                // 获取物联设备类别表单数据
                                for(let i=0, len=that.sysTypeFormList[n].formItems.length; i < len; i++) {
                                    properties.push({
                                        fcFacilitiesPropertyId : that.sysTypeFormList[n].formItems[i].id,
                                        val : that.sysTypeFormList[n].formItems[i].val,
                                        code : that.sysTypeFormList[n].formItems[i].code
                                    })
                                }
                                propertyVal.push({
                                    fcFacilitiesCategoryId: that.sysTypeFormList[n].fcfInfo.id,
				                    properties: properties
                                })
                            }
                            setFcfCPVal({
                                fcfId: res.data,
					            propertyVal: JSON.stringify(propertyVal)
                            }).then(res => {
                                that.$message({
                                    message: '保存成功！',
                                    type: 'success'
                                })
                                that.closeFun(true)
                            })
                        } else {
                            that.$message({
                                message: res.info,
                                type: 'warning'
                            })
                        }
                    })
                }
            })
            
        }
    },
    watch: {
        fireSystemTypeIdSelect(val, oldVal) {
            if(val && val !== oldVal) {
                this.getFcFacilitiesCategoryList(val)
            }
        },
        fcFacilitiesCategoryIdSelect(val, oldVal) {
            if(val && val !== oldVal) {
                this.sysTypeFormList = []
                this.getFcfCInfoList(val)
            }
        }
    },
    computed: {
        fireSystemTypeIdSelect() {
            return this.baseInfoForm.fireSystemTypeId
        },
        fcFacilitiesCategoryIdSelect() {
            return this.baseInfoForm.fcFacilitiesCategoryId
        },
    }
}
</script>
